const express = require('express')
const router = express.Router();
const multer = require('multer')
const upload = multer({ dest: 'tmp/' })
const mySql = require('../../config/db')
const path = require('path')
const fs = require('fs');
// 处理时间搓的
// const moment = require('./node_modules/moment')
// 创建个人信息
router.post('/', (req, res) => {
  const reRes = {
    status: 200,
    message: "",
    data: null
  }
  const { userName, birday, phone, addr, email, experience, imageUrl } = req.body;
  const uId = req.headers.authorization.replace(/[^0-9]/ig, "")
  // 判断该用户名是否已经创建
  const sqlSelect = "select * from user_info where u_id = ?";
  mySql.query(sqlSelect, [uId], (error, data) => {
    if (error) {
      reRes.message = '新增失败';
      reRes.data = null;
      res.json(reRes)
    } else {
      if (data.length === 0) {
        // 没有创建
        let time = Math.round((new Date().getTime()) / 1000);
        const bir = Math.round(birday / 1000);
        const sqlInsert = 'insert into user_info(u_id,user_name,birthday,phone,addr,email,experience,avatar_url,time) values(?,?,?,?,?,?,?,?,?)';
        mySql.query(sqlInsert, [uId, userName, bir, phone, addr, email, experience, imageUrl, time], (err, data) => {
          if (err) {
            reRes.message = '新增失败1';
            reRes.data = null;
            res.json(reRes)
          } else {
            // 判断是否执行成功
            if (data.affectedRows === 1) {
              reRes.message = '新增成功';
              reRes.data = data;
              res.json(reRes)
            } else {
              reRes.message = '新增失败2';
              reRes.data = null;
              res.json(reRes)
            }
          }
        })

      } else {
        reRes.message = '已经创建，不能在创建';
        reRes.data = null;
        res.json(reRes)
        // 已经创建过
      }
    }
  })
})
// 编辑个人信息
router.put('/', (req, res) => {
  const { id, userName, birday, phone, addr, email, experience, imageUrl } = req.body;
  const reRes = {
    status: 200,
    message: "",
    data: null
  }
  const uId = req.headers.authorization.replace(/[^0-9]/ig, "")
  const sqlSelect = "select u_id from user_info where id = ?";
  mySql.query(sqlSelect, [id], (err, data) => {
    if (err) {
      reRes.message = "编辑失败"
      reRes.data = null;
      res.json(reRes);
    } else {
      if (data.length === 0 || parseInt(uId) !== data[0].u_id) {
        reRes.message = "编辑失败"
        reRes.data = null;
        res.json(reRes);
      } else {
        let time = Math.round((new Date().getTime()) / 1000);
        const bir = Math.round(birday / 1000);
        sqlUpdate = `update user_info set 
        user_name = '${userName}', birthday = '${bir}',phone = '${phone}',addr = '${addr}',
        email = '${email}',experience = '${experience}',avatar_url = '${imageUrl}',time=${time} where id = ${id}`;
        mySql.query(sqlUpdate, (err, data) => {
          if (err) {
            // 修改失败
            reRes.message = '修改失败';
            reRes.data = null;
            res.json(reRes)
          } else {
            // 判断是否执行成功
            if (data.affectedRows === 1) {
              reRes.message = '修改成功';
              reRes.data = data;
              res.json(reRes)
            }
          }
        })
      }

    }
  })

})
router.get('/detail', (req, res) => {
  const reRes = {
    status: 200,
    message: "",
    data: null
  }
  const id = req.query.id
  const sqlSelect = "select * from user_info where u_id = ?";
  mySql.query(sqlSelect, [id], (err, data) => {
    if (err) {
      console.log('err=', err)
      reRes.message = '获取失败';
      reRes.data = null;
      res.json(reRes);
    } else {
      if (data.length === 0) {
        reRes.message = '没有用户信息';
        reRes.data = null;
        res.json(reRes);
      } else {
        reRes.message = '获取失败成功';
        reRes.data = data[0];
        res.json(reRes);
      }
    }
  })
})
// 获取个人基础信息列表
router.get('/list', (req, res) => {
  const reRes = {
    status: 200,
    message: "",
    data: null
  }
  const search = req.query.search ? req.query.search : '';
  const sqlList = 'select * from user_info where user_name like ? order by id desc';
  mySql.query(sqlList, [`%${search}%`], (err, data) => {
    if (err) {
      reRes = {
        status: 200,
        message: "获取失败",
        data: null
      }
      res.json(reRes)
    } else {
      if (data.length > 0) {
        reRes.message = '获取成功';
        reRes.data = data;
        res.json(reRes);
      } else {
        reRes.message = '获取成功';
        reRes.data = [];
        res.json(reRes);
      }
    }
  })
})
// 删除管理员列表
router.delete('/', (req, res) => {
  const reRes = {
    status: 200,
    message: "",
    data: null
  }
  const id = req.query.id;
  const uId = req.headers.authorization.replace(/[^0-9]/ig, "")
  const sqlSelect = "select * from user_info where u_id = ?";
  mySql.query(sqlSelect, [uId], (err, data) => {
    if (err) {
      reRes.message = "删除失败"
      reRes.data = null;
      res.json(reRes);
    } else {
      if (data.length === 0) {
        reRes.message = "文件不存在"
        reRes.data = null;
        res.json(reRes);
      } else {
        const sqlDelete = `delete from user_info where id = ${id}`;
        mySql.query(sqlDelete, (err, data) => {
          if (err) {
            reRes.message = "删除失败"
            res.json(reRes);
          } else {
            // 判断是否执行成功 
            if (data.affectedRows == 1) {
              reRes.message = "删除成功"
              reRes.data = data;
              res.json(reRes);
            } else {
              reRes.message = "删除失败"
              res.json(reRes);
            }
          }
        })
      }
    }
  })
})

// 上传图片
router.post('/uploader', upload.single('avatar'), (req, res) => {
  const reRes = {
    status: 200,
    message: "",
    data: null
  }
  // 接受文件上传数据
  const imgRes = req.file;
  // 获取文件临时目录
  const uploadPath = imgRes.path;
  // 文件上传的制定目录
  const ext = path.extname(imgRes.originalname)
  const newName = '' + (new Date().getTime()) + Math.round(Math.random() * 10000) + ext;
  const newPath = '/uploadFile/avatar/' + newName
  //进行文件的复制
  const fileData = fs.readFileSync(uploadPath);
  fs.writeFileSync(__dirname + "/../../" + newPath, fileData);
  reRes.message = '上传成功';
  reRes.data = [newPath];
  res.json(reRes);
})
module.exports = router;